package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"image/color"
	"time"
)

type snakePart2 struct {
	x, y float32
}

var (
	snakeParts2 []snakePart2
	game2       *fyne.Container
)

func main() {
	a := app.New()
	w := a.NewWindow("Snake")
	game2 = setupGame2()

	w.Resize(fyne.NewSize(400, 400))
	w.SetFixedSize(true)
	w.SetContent(game2)
	go runGame2()
	w.ShowAndRun()
}

func setupGame2() *fyne.Container {

	var segments []fyne.CanvasObject
	// 创建10个小方框
	for i := 0; i < 10; i++ {

		seg := snakePart2{9, float32(5 + i)}
		snakeParts2 = append(snakeParts2, seg)

		// 创建方框
		r := canvas.NewRectangle(&color.RGBA{G: 0x66, A: 0xff})
		// 指定方框大小
		r.Resize(fyne.NewSize(10, 10))
		// 将方框放到指定位置
		r.Move(fyne.NewPos(190, float32(50+i*10)))
		segments = append(segments, r)
	}

	return container.NewWithoutLayout(segments...)
}

func refreshGame2() {
	for i, seg := range snakeParts2 {
		rect := game2.Objects[i]
		rect.Move(fyne.NewPos(seg.x*10, seg.y*10))
	}
	game2.Refresh()
}

func runGame2() {
	for {
		time.Sleep(time.Millisecond * 250)
		for i := len(snakeParts2) - 1; i >= 1; i-- {
			snakeParts2[i] = snakeParts2[i-1]
		}
		snakeParts2[0].y--
		refreshGame2()
	}
}
